<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">
        当前位置：首页
      </el-breadcrumb-item>
      <el-breadcrumb-item>医院管理</el-breadcrumb-item>
      <el-breadcrumb-item>医院服务管理</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <div slot="header">
        <span>新增服务</span>
      </div>
      <el-form
        :model="serviceForm"
        :rules="serviceFormRules"
        ref="serviceFormRef"
        label-width="150px"
      >
        <el-form-item label="医院名称" prop="hospital_id">
          <el-select
            v-model="serviceForm.hospital_id"
            placeholder="请选择"
            filterable
            clearable
          >
            <el-option
              v-for="item in hospitalData"
              :key="item.id"
              :label="item.title + '【' + item.id + '】'"
              :value="
                typeof serviceForm.hospital_id == 'string'
                  ? item.id + ''
                  : item.id
              "
            >
            </el-option>
          </el-select>
          <el-button class="theme-background-color" @click="getServices">
            获取服务
          </el-button>
        </el-form-item>
        <el-table
          :data="serviceTableData"
          border
          style="width: 80%"
          :row-class-name="tableRowClassName"
        >
          <el-table-column prop="id" label="服务ID"></el-table-column>
          <el-table-column label="产品名称【ID】">
            <template slot-scope="scope">
              {{ scope.row.product_name }}【{{ scope.row.product_id }}】
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-link
                type="primary"
                :underline="false"
                @click="addDetail(scope.row)"
                v-if="!scope.row.status.id"
              >
                添加
              </el-link>
              <el-link :underline="false" disabled v-else>已添加</el-link>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <el-form :model="detailForm" :rules="detailFormRules" ref="detailFormRef">
        服务明细
        <el-table
          :data="detailForm.serviceDetailTableData"
          border
          style="width: 80%"
          :row-class-name="tableRowClassName"
        >
          <el-table-column
            prop="id"
            label="服务ID"
            width="100px"
          ></el-table-column>
          <el-table-column label="产品名称【ID】">
            <template slot-scope="scope">
              {{ scope.row.product_name }}【{{ scope.row.product_id }}】
            </template>
          </el-table-column>
          <el-table-column label="结算价">
            <template slot-scope="scope">
              <el-form-item
                :prop="'serviceDetailTableData.' + scope.$index + '.price'"
                :rules="detailFormRules.price"
              >
                <el-input
                  v-model="scope.row.price"
                  maxlength="8"
                  placeholder="请输入"
                ></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100px">
            <template slot-scope="scope">
              <el-link type="danger" @click="deleteService(scope.row)">
                删除
              </el-link>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <el-row>
        <el-button @click="$router.push('/hospital/HospitalServices')">
          取消
        </el-button>
        <el-button class="theme-background-color" @click="saveAllData">
          保存
        </el-button>
      </el-row>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      serviceForm: {
        hospital_id: ''
      },
      serviceFormRules: {
        hospital_id: [{ required: true, message: '请选择', trigger: 'change' }]
      },
      hospitalData: [],
      serviceTableData: [],

      detailForm: {
        serviceDetailTableData: []
      },
      detailFormRules: {
        price: [{ required: true, message: '请输入', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getSelectData()
  },
  methods: {
    async getSelectData() {
      const { data: res } = await this.$http.post('/admin/data/find', {
        code: 'get_hospital'
      })
      // 返回结果
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.hospitalData = res.data.get_hospital
    },
    getServices() {
      this.$refs.serviceFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.post(
          '/admin/dr_hospital_ser/getServiceByHostpitalId',
          {
            hospital_id: this.serviceForm.hospital_id
          }
        )
        // 返回结果
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.serviceTableData = res.data

        this.detailForm.serviceDetailTableData = []
        // 已添加数据---不需要--自作多情了
        // for (let index = 0; index < this.serviceTableData.length; index++) {
        //   const element = this.serviceTableData[index]
        //   if (element.status.id == 1) {
        //     this.detailForm.serviceDetailTableData.push({
        //       id: element.id,
        //       product_id: element.product_id,
        //       product_name: element.product_name,
        //       price: '',
        //       status: { id: 1, name: '已添加' }
        //     })
        //   }
        // }
      })
    },
    tableRowClassName({ row, rowIndex }) {
      //   把每一行的索引放进row
      row.index = rowIndex
    },
    addDetail(row) {
      row.status = { id: 1, name: '已添加' }
      this.detailForm.serviceDetailTableData.push({
        id: row.id,
        product_id: row.product_id,
        product_name: row.product_name,
        price: ''
      })
    },
    deleteService(row) {
      this.detailForm.serviceDetailTableData.splice(row.index, 1)
      for (let i = 0; i < this.serviceTableData.length; i++) {
        if (this.serviceTableData[i].id == row.id) {
          this.serviceTableData[i].status = { id: 0, name: '添加' }
          break
        }
      }
    },
    // 对部分表单字段进行校验
    validateField(form, index = '') {
      let result = true
      for (let item of this.$refs[form].fields) {
        this.$refs[form].validateField(item.prop, (error) => {
          //   console.log(item.prop)
          if (error != '') {
            result = false
          }
        })
        if (!result) break
      }
      return result
    },
    saveAllData() {
      this.$refs.serviceFormRef.validate(async (valid) => {
        if (!valid) return
        console.log(this.serviceForm, this.detailForm.serviceDetailTableData)

        if (this.detailForm.serviceDetailTableData.length == 0) {
          return this.$message.error('请添加服务明细')
        }

        if (!this.validateField('detailFormRef')) {
          return
        }
        console.log(this.detailForm.serviceDetailTableData)

        let product_ids = ''
        for (
          let i = 0;
          i < this.detailForm.serviceDetailTableData.length;
          i++
        ) {
          product_ids +=
            this.detailForm.serviceDetailTableData[i].id +
            '@' +
            this.detailForm.serviceDetailTableData[i].price
          if (i != this.detailForm.serviceDetailTableData.length - 1) {
            product_ids += ','
          }
        }
        // 向后端发起请求
        const postData = Object.assign(
          { product_ids: product_ids },
          { hospital_id: this.serviceForm.hospital_id }
        )
        const { data: res } = await this.$http.post(
          '/admin/dr_hospital_ser/add',
          postData
        )

        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success('新增服务成功')
        this.$router.push('/hospital/HospitalServices')
      })
    }
  }
}
</script>

<style lang="less" scoped>
.el-form {
  .el-select {
    width: 40%;
  }
  .el-button {
    margin-left: 10px;
  }
  /deep/.el-table th.el-table__cell {
    background-color: white !important;
    color: #909399 !important;
  }
}
</style>
